//
//  JoinQuizDetailTopView.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/14.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "JoinQuizDetailTopView.h"
#import "LotteryNumCell.h"
#import "InformationVM.h"
#import "HomePageVM.h"
#import "InformationVM.h"
@interface JoinQuizDetailTopView()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UICollectionView *collectionView;
@end

@implementation JoinQuizDetailTopView{
    QXLable     *labNum;
    QXLable     *labTime;
    QXLable     *labOldNum;
    LotteryNumType lotteryNumType;
    UIImageView *arrowImage;
    BOOL        open;
    dispatch_source_t _timer;
}

- (instancetype)initWithType:(LotteryNumType)type{
    if (self=[super init]) {
        WS(weakSelf);
        self.backgroundColor=[UIColor whiteColor];
        labOldNum=[[QXLable alloc]init];
        labOldNum.textColor=NAVCOLOR;
        [self addSubview:labOldNum];
        [labOldNum mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).with.offset(10);
            make.top.equalTo(self);
            make.height.mas_equalTo(@30);
        }];
        
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(labOldNum);
            make.right.equalTo(self);
            make.top.equalTo(labOldNum.mas_bottom).with.offset(-3);
            make.height.mas_equalTo(@30);
        }];
        
        arrowImage=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_right"]];
        [self addSubview:arrowImage];
        [arrowImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf).with.offset(-10);
            make.centerY.equalTo(labOldNum);
            make.size.mas_equalTo(arrowImage.image.size);
        }];
        
        UIButton *btn=[[UIButton alloc]init];
        [btn addTarget:self action:@selector(onclickOpen) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf);
            make.top.equalTo(self);
            make.height.mas_equalTo(@60);
        }];
        
        
        UIView *line =[[UIView alloc]init];
        line.backgroundColor=DEFAULTBGCOLOR;
        [self addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf);
            make.top.equalTo(self.collectionView.mas_bottom);
            make.height.mas_equalTo(@.7);
        }];
        
        labNum=[[QXLable alloc]init];
        [self addSubview:labNum];
        [labNum mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf).with.offset(10);
            make.top.equalTo(line.mas_bottom);
            make.height.mas_equalTo(@30);
        }];
        
        labTime=[[QXLable alloc]initWithFount:13];
        labTime.textAlignment=NSTextAlignmentRight;
        [self addSubview:labTime];
        [labTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(labNum);
            make.top.equalTo(line.mas_bottom);
            make.right.equalTo(weakSelf).with.offset(-10);
        }];
        
        UIImageView *waitImageV=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"wait"]];
        [self addSubview:waitImageV];
        [waitImageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(labTime.mas_left).with.offset(-5);
            make.centerY.equalTo(labTime);
            make.size.mas_equalTo(waitImageV.image.size);
        }];
        
        
    }
    return self;
}

- (void)setLType:(NSInteger)lType{
    _lType=lType;
    WS(weakSelf);
    [[HomePageVM manage] getLotteryInfoWithId:[NSString stringWithFormat:@"%ld",lType] Success:^(id returnValue) {
        weakSelf.currentModel=returnValue;
        labNum.text=[NSString stringWithFormat:@"当前第%@期",weakSelf.currentModel.CurrentIssue];
        labOldNum.text=[NSString stringWithFormat:@"第%@期开奖号码",weakSelf.currentModel.Issue];
        [weakSelf.collectionView reloadData];
        [weakSelf startTimer];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
    if (self.more.count==0) {
        [self getRecordList];
    }
}

- (void)getRecordList{
    WS(weakSelf);
    [[InformationVM manage] getRecordListWithId:[NSString stringWithFormat:@"%ld",self.lType] andDate:nil andPageIndex:1 Success:^(id returnValue) {
        weakSelf.more=returnValue;
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}


#pragma mark -- 启动定时器
- (void)startTimer{
    [self cancleTimer];
    [self performSelector:@selector(updateData) withObject:nil afterDelay:10];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (![self.currentModel.OpenTime isEqualToString:@"正在开奖"]) {
            NSArray *timeArr=[self.currentModel.OpenTime componentsSeparatedByString:@":"];
            int hour=[timeArr[0] intValue];
            int minutes=[timeArr[1] intValue];
            int second=[timeArr[2] intValue];
            if (second>0) {
                second-=1;
                self.currentModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else if (minutes>0){
                minutes-=1;
                second=59;
                self.currentModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else if (hour>0){
                hour-=1;
                minutes=59;
                second=59;
                self.currentModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else{
                [self cancleTimer];
                self.currentModel.OpenTime=@"正在开奖";
            }
        }else{
            [self cancleTimer];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"距离开奖时间：%@",self.currentModel.OpenTime]];
            [attStr addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(7, attStr.length-7)];
            labTime.attributedText=attStr;
            if (self.RotaryHeaderBlock) {
                self.RotaryHeaderBlock(self.currentModel.OpenTime);
            }
        });
    });
    dispatch_resume(_timer);
}

- (void)updateData{
    self.lType=self.lType;
}


- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

- (void)onclickOpen{
    if (self.openBlock) {
        open=!open;
        if (open) {
            CGAffineTransform transform =CGAffineTransformMakeRotation(M_PI/2);
            [arrowImage setTransform:transform];
        }else{
            CGAffineTransform transform =CGAffineTransformMakeRotation(M_PI*2);
            [arrowImage setTransform:transform];
        }
        
        self.openBlock(open);
    }
}

#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([self.currentModel.LType integerValue]==65) {
        return self.currentModel.PCArr.count;
    }else if ([[BaseVM manage]getType:[self.currentModel.LType integerValue]]==LotteryNumTypeLottery){
        return self.currentModel.LotteryArr.count;
    }
    return self.currentModel.numArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LotteryNumCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LotteryNumCell" forIndexPath:indexPath];
    
    LotteryNumType type=[[BaseVM manage]getType:[self.currentModel.LType integerValue]];
    if ([self.currentModel.LType integerValue]==65) {
        [cell setTitle:self.currentModel.PCArr[indexPath.row] andType:type];
    }else if (type==LotteryNumTypeLottery){
        [cell setTitle:self.currentModel.LotteryArr[indexPath.row] andType:type];
    }else{
        [cell setTitle:self.currentModel.numArr[indexPath.row] andType:type];
    }
    if ((type==LotteryNumTypeChromosphere||type==LotteryNumTypeBrings||type==LotteryNumTypeSevenLecai)&&(indexPath.row==self.currentModel.numArr.count-1)) {
        [cell setBGColor:DEFAULTTEXTBLUECOLOR];
    }else if (type==LotteryNumTypeBrings&&(indexPath.row==self.currentModel.numArr.count-2)){
        [cell setBGColor:DEFAULTTEXTBLUECOLOR];
    }
    return cell;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout =
        [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setItemSize:CGSizeMake(27, 27)];
        flowLayout.minimumLineSpacing=0;
        flowLayout.minimumInteritemSpacing=0;
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero
                                             collectionViewLayout:flowLayout];
        [_collectionView registerClass:[LotteryNumCell class] forCellWithReuseIdentifier:@"LotteryNumCell"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}

- (NSMutableArray *)more{
    if (!_more) {
        _more=[[NSMutableArray alloc]init];
    }
    return _more;
}

@end
